import hashlib
import uuid
from datetime import datetime
import platform
import socket

class SerialGenerator:
    """
    软件序列号生成器
    只用硬件信息哈希+随机+校验
    """
    
    def get_hardware_info(self):
        try:
            hostname = socket.gethostname()
            mac = uuid.getnode()
            platform_info = platform.platform()
            hardware_str = f"{hostname}_{mac}_{platform_info}"
            return hashlib.md5(hardware_str.encode()).hexdigest()[:8].upper()
        except Exception:
            return "DEFAULT01"

    def generate_random_component(self):
        random_uuid = str(uuid.uuid4()).replace('-', '')
        return random_uuid[:6].upper()

    def generate_checksum(self, serial_base):
        checksum = 0
        for char in serial_base:
            checksum += ord(char)
        checksum = checksum % 100
        return f"{checksum:03d}"

    def generate_serial(self):
        # 格式: HHHHHHHH-RRRRRR-CC
        hardware = self.get_hardware_info()
        random_comp = self.generate_random_component()
        serial_base = f"{hardware}{random_comp}"
        checksum = self.generate_checksum(serial_base)
        serial = f"{hardware}-{random_comp}-{checksum}"
        return serial

    def validate_serial(self, serial):
        try:
            parts = serial.split('-')
            if len(parts) != 3:
                return False
            hardware, random_comp, checksum = parts
            serial_base = f"{hardware}{random_comp}"
            expected_checksum = self.generate_checksum(serial_base)
            return checksum == expected_checksum
        except Exception:
            return False

    def get_serial_info(self, serial):
        if not self.validate_serial(serial):
            return None
        try:
            parts = serial.split('-')
            hardware, random_comp, checksum = parts
            return {
                'hardware_hash': hardware,
                'random_component': random_comp,
                'checksum': checksum,
                'is_valid': True
            }
        except Exception:
            return None

if __name__ == "__main__":
    generator = SerialGenerator()
    serial = generator.generate_serial()
    print(f"生成的序列号: {serial}")
    is_valid = generator.validate_serial(serial)
    print(f"序列号有效: {is_valid}")
    info = generator.get_serial_info(serial)
    if info:
        print("序列号信息:")
        for key, value in info.items():
            print(f"  {key}: {value}") 